# encoding=utf-8
import datetime
import os
import traceback

from seg_system import ApplicationConfig
from nb_log import get_logger


"""
    Author: tacom
    Date: 2023.2.6
    Description: 
        由于暂时无法解决日志写入过多报错的问题，
        以及try...exception使用以后导致的位置不对问题
        现在暂时混用以下两个类
        
        1. 常规的输出debugger, info通过ConsoleBuilder
           实例化log对象后直接输出
        2. 对于Exception,Error等首先通过ConsoleService
           保证完成输出一次(写入文件方便分析)，然后再通过log对象输出
           也可以直接使用ConsoleService而不使用log对象
"""


class ConsoleService:
    """
        @TODO Bug,无法随天数增加，自动更换日志文件

    """
    DEBUG = 1
    INFO = 2
    WARNING = 3
    ERROR = 4
    CRITICAL = 5
    EXCEPTION = 6

    console_logger = get_logger(name='ConsoleLog', is_add_stream_handler=True,
                                log_path=os.path.join(ApplicationConfig.PathConfig.SYSTEM_RESOURCE,
                                                      ApplicationConfig.PathConfig.SYSTEM_LOG_FOLDER),
                                log_filename=ApplicationConfig.PathConfig.SYSTEM_LOG_FILE)

    @staticmethod
    def try_log(f, m: str):
        try:
            f(m)
        except Exception as e:
            print(traceback.format_exc())

    @staticmethod
    def console_log(message: str, level: int = DEBUG):
        if level == ConsoleService.DEBUG:
            # ConsoleService.console_logger.debug(message)
            ConsoleService.try_log(ConsoleService.console_logger.debug, message)
        elif level == ConsoleService.INFO:
            ConsoleService.try_log(ConsoleService.console_logger.info, message)
            # ConsoleService.console_logger.info(message)
        elif level == ConsoleService.WARNING:
            ConsoleService.try_log(ConsoleService.console_logger.warning, message)
            # ConsoleService.console_logger.warning(message)
        elif level == ConsoleService.ERROR:
            ConsoleService.try_log(ConsoleService.console_logger.error, message)
            # ConsoleService.console_logger.error(message)
        elif level == ConsoleService.CRITICAL:
            # ConsoleService.console_logger.critical(message)
            ConsoleService.try_log(ConsoleService.console_logger.critical, message)
        elif level == ConsoleService.EXCEPTION:
            ConsoleService.try_log(ConsoleService.console_logger.exception, message)
        else:
            print(message)

    @staticmethod
    def get_logger():
        return ConsoleService.console_logger

    @staticmethod
    def make_logger():
        file_name = "Consolelog{}.txt".format(datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S"))
        ConsoleService.console_logger = \
            get_logger(name='ConsoleLog', is_add_stream_handler=True,
                       log_path=os.path.join(ApplicationConfig.PathConfig.SYSTEM_RESOURCE,
                                             ApplicationConfig.PathConfig.SYSTEM_LOG_FOLDER),
                       log_filename=file_name)
        ConsoleService.console_logger.info('logger update !!, name is: {}'.format(file_name))


class ConsoleBuilder:
    """
        nb_log经过封装以后，无法正常显示调用处的真实函数
        ConsoleBuilder通过返回函数指针，由用户进行调用
        从而解决这个问题(失败)

        @TODO python的logger模块存在异步问题，当写入量太大时
              会出现log报错，但用try进行封装时，代码提示不准确
    """

    def __init__(self, name: str):
        self.logger = get_logger(name=name,
                                 log_path=os.path.join(ApplicationConfig.PathConfig.SYSTEM_RESOURCE,
                                                       ApplicationConfig.PathConfig.SYSTEM_LOG_FOLDER),
                                 log_filename=ApplicationConfig.PathConfig.SYSTEM_LOG_FILE)

    @staticmethod
    def get_logger(name: str):
        return get_logger(name=name,
                          log_path=os.path.join(ApplicationConfig.PathConfig.SYSTEM_RESOURCE,
                                                ApplicationConfig.PathConfig.SYSTEM_LOG_FOLDER),
                          log_filename=ApplicationConfig.PathConfig.SYSTEM_LOG_FILE)

    def try_wrapper(self, f):
        def wrapper(*args):
            try:
                f(*args)  # 仍然失效
            except:
                print(traceback.format_exc())
        return wrapper

    def debugger(self):
        return self.try_wrapper(self.logger.debug)

    def info(self):
        return self.try_wrapper(self.logger.info)

    def warning(self):
        return self.try_wrapper(self.logger.warning)

    def exception(self):
        return self.try_wrapper(self.logger.exception)


# if __name__ == '__main__':
#     builder = ConsoleBuilder("test")
#     builder.debugger("hh")
